package com.pktechan.manage.utils.ueditor;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;


@Controller
@RequestMapping("/ueditor")
public class UeditorController {


	/**
	 * 加载ueditor的配置
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = { "/toUpload" })
	public String toUploads(HttpServletRequest request) {
		String rootPath = request.getServletContext().getContextPath();
		return new ActionEnter(request, rootPath).exec();
	}

//	/**
//	 * 根据文件key获取文件信息
//	 *
//	 * @param request
//	 * @param response
//	 */
//	@RequestMapping(value = { "/getFileByFileKey/{fullPath}" }, method = { RequestMethod.GET })
//	public void getFileByFileKey(@ModelAttribute("fullPath") String fullPath, HttpServletRequest request,
//			HttpServletResponse response) {
//		InputStream in = null;
//		try {
//			// 1：获取文件流
//			in = fileUploadFastdfs.downloadFile(fullPath);
//			// 2：写出
//			if (in != null) {
//				outFileInputStream(in, response);
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}

	/**
	 * 写出文件流
	 *
	 * @param in
	 * @param response
	 */
	public void outFileInputStream(InputStream in, HttpServletResponse response) {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			// 1：初始流
			response.setContentType("image/jpeg");
			bis = new BufferedInputStream(in);
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[1024];
			int bytesRead = 0;
			// 2：流式获取内容并流式输出
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception err) {
			err.printStackTrace();
		} finally {
			closeIo(bis, bos);
		}
	}

	public void closeIo(BufferedInputStream bis, BufferedOutputStream bos) {
		try {
			if (bis != null) {
				bis.close();
			}
		} catch (Exception err) {
			err.printStackTrace();
		}
		try {
			if (bos != null) {
				bos.close();
			}
		} catch (Exception err) {
			err.printStackTrace();
		}
	}
}
